package com.zjxf.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.zjxf.base.bean.po.CmsSchoolNews;
import com.zjxf.base.bean.po.UmsStoreSeller;
import com.zjxf.base.bean.ro.RoCmsSchoolNews;
import com.zjxf.base.bean.sort.SortDto;
import com.zjxf.base.bean.sort.SortUtils;
import com.zjxf.base.bean.vo.VoCmsSchoolNews;
import com.zjxf.base.common.OperationException;
import com.zjxf.base.common.SysConst;
import com.zjxf.repository.CmsSchoolNewsRepository;
import com.zjxf.service.CmsSchoolNewsService;
import com.zjxf.utils.Conversion;
import com.zjxf.utils.DynamicSpecifications;
import com.zjxf.utils.PageUtils;
import com.zjxf.utils.SearchFilter;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 新闻
 *
 * @author ZhangWei
 * @date 2021/4/6/006 10:52
 */
@Service
@AllArgsConstructor
@Transactional(rollbackOn = RuntimeException.class)
public class CmsSchoolNewsServiceImpl implements CmsSchoolNewsService {

    private final CmsSchoolNewsRepository cmsSchoolNewsRepository;

    public Optional<CmsSchoolNews> findById(Long id) {
        return cmsSchoolNewsRepository.findByIdAndDeleteState(id, SysConst.DeleteState.UN_DELETE_STATE.getCode());
    }

    @Override
    public void addOrUpdate(VoCmsSchoolNews.addOrUpdate vo, UmsStoreSeller umsStoreSeller) {
        Optional<CmsSchoolNews> optionalCmsLmSchoolNews = findById(vo.getId());
        CmsSchoolNews cmsSchoolNews;
        if (optionalCmsLmSchoolNews.isPresent()) {
            cmsSchoolNews = optionalCmsLmSchoolNews.get();
            Conversion.voTurnPo(vo, cmsSchoolNews);
            cmsSchoolNews.setUpdateTime(LocalDateTime.now());
            cmsSchoolNews.setPublisherId(umsStoreSeller.getId());
        } else {
            cmsSchoolNews = new CmsSchoolNews();
            Conversion.voTurnPo(vo, cmsSchoolNews);
            cmsSchoolNews.setStoreId(umsStoreSeller.getStoreId());
            cmsSchoolNews.setPublisherId(umsStoreSeller.getId());
            cmsSchoolNews.setVerifyStatus(SysConst.VerifyStatus.IN_REVIEW.getCode());
        }
        cmsSchoolNewsRepository.save(cmsSchoolNews);
    }

    @Override
    public void delete(Long id) throws OperationException {
        CmsSchoolNews cmsSchoolNews = findById(id).orElseThrow(() -> new OperationException(SysConst.DATA_NOT_FOND));
        cmsSchoolNews.setDeleteState(SysConst.DeleteState.DELETE_STATE.getCode());
        cmsSchoolNewsRepository.save(cmsSchoolNews);
    }

    @Override
    public CmsSchoolNews getEntity(Long id) throws OperationException {
        return findById(id).orElseThrow(() -> new OperationException(SysConst.DATA_NOT_FOND));
    }

    @Override
    public RoCmsSchoolNews.Details getEntityRo(CmsSchoolNews CmsSchoolNews) {
        return Conversion.poTurnRo(CmsSchoolNews, new RoCmsSchoolNews.Details());
    }

    @Override
    public Page<CmsSchoolNews> page(VoCmsSchoolNews.filter filter,UmsStoreSeller umsStoreSeller) {
        List<SearchFilter> searchFilters = new ArrayList<>();
        searchFilters.add(new SearchFilter("storeId", SearchFilter.Operator.EQ,umsStoreSeller.getStoreId()));
        if (StringUtils.isNotBlank(filter.getKeywords())) {
            searchFilters.add(new SearchFilter("title", SearchFilter.Operator.LIKE, filter.getKeywords()));
        }
        if (filter.getShowState() != null) {
            searchFilters.add(new SearchFilter("showState", SearchFilter.Operator.EQ, filter.getShowState()));
        }
        if (filter.getVerifyStatus() != null) {
            searchFilters.add(new SearchFilter("verifyStatus", SearchFilter.Operator.EQ, filter.getVerifyStatus()));
        }
        if (filter.getType() != null) {
            searchFilters.add(new SearchFilter("type", SearchFilter.Operator.EQ, filter.getType()));
        }
        Specification<CmsSchoolNews> specification = DynamicSpecifications.bySearchFilterByBasic(searchFilters, filter.getStartTime(), filter.getEndTime());
        SortUtils.basicSort(
                new SortDto(SysConst.SortOrder.DESC.getCode(), "showState"),
                new SortDto(SysConst.SortOrder.DESC.getCode(), "type"),
                new SortDto(SysConst.SortOrder.DESC.getCode(), "createTime")
        );
        return cmsSchoolNewsRepository.findAll(specification, PageUtils.buildPageRequest(filter.getPageNum(), filter.getPageSize()));
    }

    @Override
    public JSONObject pageRo(Page<CmsSchoolNews> cmsLmSchoolNewsPage) {
        List<CmsSchoolNews> pageList = cmsLmSchoolNewsPage.getContent();
        List<RoCmsSchoolNews.Page> roList = pageList.stream().map(item -> Conversion.voTurnPo(item, new RoCmsSchoolNews.Page())).collect(Collectors.toList());
        return PageUtils.page(cmsLmSchoolNewsPage, roList);
    }

    @Override
    public void switchShow(VoCmsSchoolNews.SwitchShow vo) throws OperationException {
        CmsSchoolNews cmsSchoolNews = findById(vo.getId()).orElseThrow(() -> new OperationException(SysConst.DATA_NOT_FOND));
        cmsSchoolNews.setShowState(vo.getShowState());
        cmsSchoolNewsRepository.save(cmsSchoolNews);
    }
}
